package com.ld.task;

import java.util.LinkedList;
import java.util.concurrent.Exchanger;
import java.util.concurrent.Semaphore;

/**
 * UseSemaphore:模拟数据库链接池的实现
 */
public class UseSemaphore {

    LinkedList<SimulateCollection> pool = new LinkedList<>();

    private Semaphore useful;
    private Semaphore already;

    //    public UseSemaphore(Semaphore useful,Semaphore already){
//        this.useful = useful;
//        this.already = already;
//    }
    public UseSemaphore(int linkNum) {
        if(linkNum<=0){
            linkNum=6;
        }
        this.useful = new Semaphore(linkNum);
        this.already = new Semaphore(0);
    }

    //获取数据库链接
    public SimulateCollection getCollection() throws InterruptedException {
        useful.acquire();
        SimulateCollection collection = null;
        synchronized (pool) {
            if (pool.size() > 0) {
                collection = pool.removeFirst();
            }
        }
        already.release();
        return collection;
    }

    //释放数据库链接资源
    public SimulateCollection releaseCollection(SimulateCollection collection) throws InterruptedException {
        already.acquire();
        synchronized (pool) {
            if (collection != null) {
                pool.addLast(collection);
            }
        }
        useful.release();
        return collection;
    }
}
